<template>
	<view class="u-p-l-20 u-p-r-20 u-p-t-10">
		<view class="container">
			<!-- 购物车集合 -->
			<view class="cartItem u-p-t-10 u-p-b-10 u-flex" v-for="(item,index) in cartList" :key="item._id">
				<view class="left u-text-center">
					<u-checkbox v-model="item.is_checked === true ? true : false" :name="item._id" @change="changCheck(index)" shape="circle" size="40"></u-checkbox>
				</view>
				<view class="image">
					<!-- 商品图片 -->
					<u-image width="200rpx" height="240rpx" border-radius="20"
						:src="item.cover_url"></u-image>
				</view>
				<view class="right u-flex u-flex-col u-fl u-flex-1">
					<view class="top u-flex u-flex-col">
						<!-- 商品标题 -->
						<text class="title">{{item.title}}</text>
						<!-- <text class="desc">{{item.title}}</text> -->
					</view>
					<view class="bottom u-p-b-20 u-flex u-flex-1 u-col-bottom u-row-around">
						<view class="price">
							<!-- 价格 -->
							￥{{item.price}}
						</view>
						<view class="num u-m-l-10 u-m-r-10" style="width: 200rpx;">
							<!-- 购物车集合元素 -->
							<u-number-box v-model="item.num" @minus="handleNum(item)" @plus="handleNum(item)"></u-number-box>
						</view>
						<!-- 购物车集合元素id -->
						<view class="icon" @click="del(item.cart_id)">
							<u-icon name="trash" size="40"></u-icon>
						</view>
					</view>
				</view>
			</view>
		</view>
			<view class="bottomFixed u-flex u-p-15">
				<view class="u-flex-5">
					<u-checkbox v-model="allCheck" size="40" shape="circle">全选</u-checkbox>
				</view>
				<view class="u-flex u-flex-7 u-row-around">
					<view>
						<text class="title">合计:</text>
						<!-- totalPrice -->
						<text class="price">￥{{totalPrice}}</text>
					</view>
					<u-button type="primary" :ripple="true" shape="square" disabled>去结算</u-button>
				</view>
			</view>
		
		<u-modal v-model="show" content="确认要移除商品吗？" :show-cancel-button="true" @cancel="show = false" @confirm="confirm"></u-modal>
	</view>
</template>

<script>
	const db=uniCloud.database();
	export default {
		data() {
			return {
				cartId: '',// 要删除的id
				cartList: [],// 购物车数据列表
				show: false,// 删除提示
				
			}
		},
		
		computed:{
			//合计
			totalPrice(){
				let sum = 0;
				 this.cartList.filter(item => {
					return item.is_checked ? true : false;
				}).map(item=>{
					sum+=item.price*item.num
				})
				return sum;
			},
			// 全选或全不选
			allCheck: {
				get(){
					return this.cartList.every(item => {
						return item.is_checked;
					});
				},
				set(val){
					this.checkAll(val)
				}
			}
		},
		onLoad() {
			// this.getCartList()
			// console.log("24324")
		},
		onShow(){
			this.getCartList()
			// console.log("24324")
		},
		methods: {
			// 获取购物车数据
			async getCartList(){
				// const res = await this.$u.api.cartsList()
				// this.cartList = res.data
				let res = await db.collection("cart","goods_detail").where({
					user_id:uni.getStorageSync('storage_user')._id
				}).get();
				let arr = [];
				for(let i in res.result.data){
					arr =  arr.concat(res.result.data[i].goods_id);
					arr[i].num = res.result.data[i].num;
					arr[i].cart_id = res.result.data[i]._id;
					arr[i].is_checked = res.result.data[i].is_checked;
				}
				this.cartList = arr;
				// let arr=[];
				// if(res.result.data.length){
				// 	for(let i in res.result.data){
				// 		let realResult=await db.collection("goods_detail").where({
				// 			_id:res.result.data[i].goods_id
				// 		}).get();
				// 		if(realResult.result.data.length){
				// 			arr =  realResult.result.data;
				// 			// console.log(this.cartList)
				// 		}
				// 	}
					
				// }
				// this.cartList=arr
				// console.log(">>>>>>>>>>>>>>>>",this.cartList)
			},
			// 移除购物车数据
			async del(id) {
				this.show = true
				this.cartId = id
			},
			async confirm(){
				let res = await db.collection("cart").where({
					_id:this.cartId
				}).remove();
				if(!res.result.code){
					this.$u.toast('移除商品成功')
					this.getCartList();
				}
			},
			//单选
			async changCheck(index){
				let check = !this.cartList[index].is_checked;
				let res=await db.collection("cart").where({
					_id:this.cartList[index].cart_id
				}).update({is_checked:check});
				if(!res.result.code){
					this.cartList[index].is_checked = check;
				}
			},
			
			// 全选/全不选
			async checkAll(val){
				console.log("val",val)
				db.collection("cart").where({
					user_id:uni.getStorageSync('storage_user')._id
				}).update({
					is_checked:val
				}).then(res=>{
					if(!res.result.code){
						this.getCartList()	
					}
					
				})
			
				
			},
			
			// 数量增加或减少
			async handleNum(item){
				// await this.$u.api.cartsNum(item.id,{num: item.num})
				db.collection("cart").where({
					_id:item.cart_id
				}).update({
					num:item.num
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.container {
		height: calc(100vh - 298rpx);
		overflow-y: scroll;
		.cartItem {
			
			border: 1rpx solid #eee;
			border-radius: 20rpx;
			margin-bottom: 20rpx;

			.left {
				width: 80rpx;
				height: 80rpx;
				padding: 10rpx;
			}

			.image {}

			.right {
				// flex-direction: column;
				height: 240rpx;
				align-items: flex-start;

				.top {
					width: 100%;

					text {
						height: 40rpx;
						line-height: 40rpx;
						width: 100%;
						text-align: left;
					}
				}

				.bottom {
					width: 100%;

					.price {
						height: 50rpx;
						line-height: 50rpx;
						overflow: hidden;
						color: red;
						font-weight: bold;
						font-size: 35rpx;
					}

					.icon {
						color: red;
						width: 40rpx;
					}
				}



			}
		}
	}

	.footer {
		position: fixed;
		display: flex;
		bottom: 0;
		height: 100rpx;
		line-height: 100rpx;
		width: 100%;
	}
	.bottomFixed {
		position: fixed;
		left: 0;
		right: 0;
		background-color: #fff;
	}
</style>

<!-- <template>
	<view class="wrap">
		<template v-if="vuex_token">
			<view v-if="goodsList.length" class="cartGoodsList u-p-b-80">
				<view class="cartGoods u-flex u-p-15" v-for="goods in goodsList" :key="goods.id">
					<view>
						<u-checkbox v-model="goods.is_checked?true:false" :name="goods.id" @change="checkChange"
							size="40" shape="circle"></u-checkbox>
					</view>
					<view class="goodsInfo u-flex u-p-10">
						<view @tap='jump(`/pages/goods/goods-detail/goods-detail`,goods.goods_id)'>
							<u-image border-radius="15" width="200rpx" height="200rpx" :src="goods.goods.cover_url">
							</u-image>
						</view>
						<view class="goodsBaseInfo u-flex u-row-between u-col-top u-p-10">
							<view class="priceNum" @tap='jump(`/pages/goods/goods-detail/goods-detail`,goods.goods_id)'>
								<text class="title u-p-l-10 u-font-32">{{goods.goods.title}}</text>
								<br>
								<text class="small">{{goods.goods.description}}</text>
								<view class="u-text-right small">
									库存:<text style="color:red">{{goods.goods.stock}}</text>
								</view>
							</view>
							<view class="priceNum u-flex u-row-between">
								<text class="price u-font-34">￥{{goods.goods.price}}</text>
								<u-number-box v-model="goods.num" :min="1" :max="goods.goods.stock" :index="goods.id"
									@change="numChange"></u-number-box>
								<u-icon @tap="removeGoods(goods.id)" name="trash" color="#e83333" size="36">
								</u-icon>
							</view>
						</view>
					</view>
				</view>
			</view>
			<view class="empty" v-else>
				<u-empty text="购物车空空如也" mode="car"></u-empty>
			</view>
			<view class="bottomFixed u-flex u-p-15">
				<view class="u-flex-5">
					<u-checkbox v-model="allCheck" size="40" shape="circle">全选</u-checkbox>
				</view>
				<view class="u-flex u-flex-7 u-row-around">
					<view>
						<text class="title">合计:</text>
						<text class="price">￥{{totalPrice}}</text>
					</view>
					<u-button type="primary" :ripple="true" shape="square" disabled>去结算</u-button>
				</view>
			</view>
		</template>
		<template v-else>
			<u-empty text="暂未登入" mode="permission"></u-empty>
		</template>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				goodsList: [],
			};
		},
		onShow() {
			if (this.vuex_token) {
				this.getCartGoods()
			}
		},
		computed: {
			// 全选和全不选判断
			allCheck: {
				get() {
					return this.goodsList.every((goods) => {
						return goods.is_checked
					})
				},
				set(val) {
					this.checkApi(val)
				}
			},
			// 选中商品的总价
			totalPrice() {
				return this.goodsList.filter((goods) => { //过滤掉没有选中商品
					if (goods.is_checked) {
						return true
					}
				}).reduce((pre, goods) => { //价格累加
					return parseInt(pre) + parseInt(goods.goods.price) * goods.num //乘商品数量
				}, 0)
			}
		},
		methods: {
			// 商品详情跳转
			jump(url, id) {
				this.$u.route({
					url,
					params: {
						id
					}
				})
			},
			// 获取购物车内商品
			async getCartGoods() {
				const {
					data
				} = await this.$u.api.cartGoods()
				this.goodsList = data
				// console.log(data)
			},
			// 商品数量改变
			async numChange(val) {
				// 通过设置index获取（购物车商品的id）既val中第二参数
				const {
					value,
					index
				} = val
				await this.$u.api.numChange(index, String(value))
			},
			// 移出购物车
			async removeGoods(id) {
				// delCartGoods
				await this.$u.api.delCartGoods(id)
				// 删除商品后进行提示   再次调用获取商品列表
				this.$u.toast("移出购物车成功")
				this.getCartGoods()
			},
			// 单个商品是否选中
			async checkChange(val) {
				const {
					value,
					name
				} = val
				let idArr = [];
				// 先把已经选中的商品id存入idArr内
				this.goodsList.forEach((goods) => {
					if (goods.is_checked) {
						idArr.push(goods.id)
					}
				})
				if (!value) {
					//选中状态，点击后变成false
					idArr.splice(idArr.indexOf(name), 1)
					await this.$u.api.isCheck(idArr)
				} else {
					//没选中中状态，点击后变成true
					idArr.push(name)
					await this.$u.api.isCheck(idArr)
				}
				// 最后重新调用获取商品数据更新
				this.getCartGoods()
			},
			// 全选与全不选接口调用
			async checkApi(val) {
				// 准备获取各个购物车id参数
				let idArr = []
				if (!val) {
					// 全选点击（变全不选）
					idArr = []
					await this.$u.api.isCheck(idArr)
				} else {
					// 全不选选点击（变全选）
					this.goodsList.forEach((goods) => {
						idArr.push(goods.id)
					})
					await this.$u.api.isCheck(idArr)
				}
				// 最后重新调用获取商品数据更新
				this.getCartGoods()
			},

		}
	}
</script>

<style scoped lang="scss">
	.wrap {
		min-height: 80vh;
		.empty {
			height: 80vh;
		}

		.loading {
			text-align: center;
			position: absolute;
			top: 50%;
			left: 50%;
			transform: translate(-50%, -50%);
		}

		.title,
		.price {
			font-weight: 800;
		}

		.price {
			color: #e83333;
		}

		.cartGoodsList {
			.cartGoods {
				.goodsInfo {
					width: 100%;
					background-color: rgb(251, 250, 251);

					.goodsBaseInfo {
						width: 100%;
						height: 200rpx;
						flex-direction: column;

						.priceNum {
							width: 100%;

						}
					}
				}
			}
		}

		.bottomFixed {
			position: fixed;
			left: 0;
			right: 0;
			background-color: #fff;
		}

		/*#ifdef H5*/
		.bottomFixed {
			bottom: 100rpx;
		}

		/*#endif*/
		/*#ifdef MP-WEIXIN*/
		.bottomFixed {
			bottom: 0;
			z-index: 99999;
		}

		/*#endif*/

	}
</style>
 -->